require"pins"
require"audio"
module(..., package.seeall)

audio.setStrategy(1)

--pio.pin.setdebounce(0)
keys = {}
for i=1,16 do keys[i] = 0 end

--按键回调
local function keyCB(key)
    sys.publish("KEY_PRESS",key,keys[key])
    if keys[key] == 1 then
        --audio.play(0,"TTS",tostring(key),3)
    end
end

local scl = pins.setup(14, 0)
local sdo = pins.setup(15, function (msg)
    log.info("sdo input", msg)
end)

sys.timerLoopStart(function ()
    local events = {}
    for i=1,16 do
        scl(1)
        scl(0)
        if keys[i] ~= sdo() then
            keys[i]=sdo()
            table.insert(events,i)
        end
    end
    for i=1,#events do
        keyCB(events[i])
    end
end, 50)


--显示按键状态
--每格32*32
local function show()
    disp.clear()
    disp.drawrect(0,0,127,127,0x00ff)
    for i=1,16 do
        local x = (i-1)%4
        local y = ((i-1)-(i-1)%4)/4
        if keys[i] == 1 then
            disp.drawrect(x*32,y*32,(x+1)*32,(y+1)*32,0xff00)
        end
        disp.puttext(tostring(i),x*32+10,y*32+10)
    end
    for i=1,3 do
        disp.drawrect(0,i*32,127,i*32,0)
        disp.drawrect(i*32,0,i*32,127,0)
    end
    disp.update()
end

show()
sys.subscribe("KEY_PRESS",function ()
    show()
end)
